using System.Collections;
using GHIElectronics.NETMF.Glide.UI;
using GHIElectronics.NETMF.Glide;
using Melody_Glider.MelodyContent;
using Microsoft.SPOT;

namespace Melody_Glider.GUIContent
{
    class EditorWindow: WindowFrame //todo: optimisation of everything
    {
        private readonly GUI _gui;
        private readonly SystemState _conditions;
        private StaffDrawer _staffDrawer;
        public const int MelodyFieldBound = 279;
        public const int CursorWidth = 5;
        public int DrawingStartIndex; //todo: to private or to SystemState
        public int XPos; //todo: as above
        public int DisplayedNoteCounter; //todo: as above
        
        private readonly Hashtable _noteImageResources = new Hashtable
        {
            {"fullNoteTh", Resources.GetBitmap(Resources.BitmapResources.fullNoteTh)},
            {"fullNoteTh_1", Resources.GetBitmap(Resources.BitmapResources.fullNoteTh_1)},
            {"halfNoteTh", Resources.GetBitmap(Resources.BitmapResources.halfNoteTh)},
            {"halfNoteTh_1", Resources.GetBitmap(Resources.BitmapResources.halfNoteTh_1)},
            {"quarterNoteTh", Resources.GetBitmap(Resources.BitmapResources.quarterNoteTh)},
            {"quarterNoteTh_1", Resources.GetBitmap(Resources.BitmapResources.quarterNoteTh_1)},
            {"eighthNoteTh", Resources.GetBitmap(Resources.BitmapResources.eighthNoteTh)},
            {"eighthNoteTh_1", Resources.GetBitmap(Resources.BitmapResources.eighthNoteTh_1)},
            {"sixteenthNoteTh", Resources.GetBitmap(Resources.BitmapResources.sixteenthNoteTh)},
            {"sixteenthNoteTh_1", Resources.GetBitmap(Resources.BitmapResources.sixteenthNoteTh_1)},
            {"fullRestTh", Resources.GetBitmap(Resources.BitmapResources.fullRestTh)},
            {"fullRestTh_1", Resources.GetBitmap(Resources.BitmapResources.fullRestTh_1)},
            {"halfRestTh", Resources.GetBitmap(Resources.BitmapResources.halfRestTh)},
            {"halfRestTh_1", Resources.GetBitmap(Resources.BitmapResources.halfRestTh_1)},
            {"quarterRestTh", Resources.GetBitmap(Resources.BitmapResources.quarterRestTh)},
            {"quarterRestTh_1", Resources.GetBitmap(Resources.BitmapResources.quarterRestTh_1)},
            {"eighthRestTh", Resources.GetBitmap(Resources.BitmapResources.eighthRestTh)},
            {"eighthRestTh_1", Resources.GetBitmap(Resources.BitmapResources.eighthRestTh_1)},
            {"sixteenthRestTh", Resources.GetBitmap(Resources.BitmapResources.sixteenthRestTh)},
            {"sixteenthRestTh_1", Resources.GetBitmap(Resources.BitmapResources.sixteenthRestTh_1)},
            {"sharpTh", Resources.GetBitmap(Resources.BitmapResources.sharpTh)},
            {"sharpTh_1", Resources.GetBitmap(Resources.BitmapResources.sharpTh_1)},
            {"flatTh", Resources.GetBitmap(Resources.BitmapResources.flatTh)},
            {"flatTh_1", Resources.GetBitmap(Resources.BitmapResources.flatTh_1)},
            {"dotTh", Resources.GetBitmap(Resources.BitmapResources.dotTh)},
            {"dotTh_1", Resources.GetBitmap(Resources.BitmapResources.dotTh_1)},
            {"staccatoTh", Resources.GetBitmap(Resources.BitmapResources.dotTh)},
            {"staccatoTh_1", Resources.GetBitmap(Resources.BitmapResources.dotTh_1)}
        };
        
        public EditorWindow(GUI gui, SystemState state)
        {
            _gui = gui;
            _conditions = state;
        }

        protected override void SophisticatedInit()
        {
            _conditions.SelectedNote = -1;
            _staffDrawer = new StaffDrawer(this, ThisWindow, _conditions);
        }
        
        protected override void InitButtons() //woah...
        {
            var saveBtn = (Button)ThisWindow.GetChildByName("SaveButton");
            saveBtn.TapEvent += SaveBtnTapEvent;

            var clrBtn = (Button)ThisWindow.GetChildByName("ClrButton");
            clrBtn.TapEvent += ClrBtnTapEvent;

            var quitBtn = (Button)ThisWindow.GetChildByName("QuitButton");
            quitBtn.TapEvent += QuitBtnTapEvent;

            var addBtn = (Button)ThisWindow.GetChildByName("AddButton");
            addBtn.TapEvent += AddBtnTapEvent;

            var delBtn = (Button)ThisWindow.GetChildByName("DelButton");
            delBtn.TapEvent += DelBtnTapEvent;

            var replBtn = (Button)ThisWindow.GetChildByName("ReplaceButton");
            replBtn.TapEvent += ReplBtnTapEvent;

            var playBtn = (Button)ThisWindow.GetChildByName("PlayButton");
            playBtn.TapEvent += PlayBtnTapEvent;

            var playNoteBtn = (Button)ThisWindow.GetChildByName("PlayNoteButton");
            playNoteBtn.TapEvent += PlayNoteBtnTapEvent;

            var nameBox = (TextBox)ThisWindow.GetChildByName("NameBox");
            nameBox.TapEvent += NameBoxTapEvent;

            var baseOctaveBox = (TextBox)ThisWindow.GetChildByName("BaseOctaveBox");
            baseOctaveBox.TapEvent += BaseOctaveBoxTapEvent;

            var bpmBox = (TextBox)ThisWindow.GetChildByName("BpmBox");
            bpmBox.TapEvent += BpmBoxTapEvent;

            var leftBtn = (Button)ThisWindow.GetChildByName("ScrollLeft");
            leftBtn.TapEvent += LeftBtnTapEvent;

            var rightBtn = (Button)ThisWindow.GetChildByName("ScrollRight");
            rightBtn.TapEvent += RightBtnTapEvent;

            var toStartBtn = (Button)ThisWindow.GetChildByName("ToStart");
            toStartBtn.TapEvent += ToStartBtnTapEvent;

            var toEndBtn = (Button)ThisWindow.GetChildByName("ToEnd");
            toEndBtn.TapEvent += ToEndBtnTapEvent;

            var octaveUpBtn = (Button)ThisWindow.GetChildByName("OctaveUp");
            octaveUpBtn.TapEvent += OctaveUpBtnTapEvent;

            var octaveDownBtn = (Button)ThisWindow.GetChildByName("OctaveDown");
            octaveDownBtn.TapEvent += OctaveDownBtnTapEvent;

            var cloneBtn = (Button)ThisWindow.GetChildByName("CloneButton");
            cloneBtn.TapEvent += CloneBtnTapEvent;

            var copyBtn = (Button)ThisWindow.GetChildByName("CopyButton");
            copyBtn.TapEvent += CopyBtnTapEvent;

            var pasteBtn = (Button)ThisWindow.GetChildByName("PasteButton");
            pasteBtn.TapEvent += PasteBtnTapEvent;
        }

        protected override void PrepareToMain()
        {
            _staffDrawer.ClearMelodyField();
            XPos = 43;
            _staffDrawer.DrawMelodyField();
            
            Refresh();
            UpdateScrollBtns();

            if (CursorVisible())
                HighlightCursor();
            if (NoteVisible())
                HighlightNote();
        }

        private void Refresh()
        {
            var bpmText = (TextBox)ThisWindow.GetChildByName("BpmBox");
            if (_conditions.NewBpm)
                bpmText.Text = "bpm";
            else
                bpmText.Text = _conditions.MelodyBuffer.GetBpm().ToString();
            bpmText.Invalidate();

            var baseOctaveText = (TextBox)ThisWindow.GetChildByName("BaseOctaveBox");
            if (_conditions.NewBaseOctave)
                baseOctaveText.Text = "base octave";
            else
                baseOctaveText.Text = _conditions.MelodyBuffer.GetBaseOctave().ToString();
            baseOctaveText.Invalidate();

            var fileNameText = (TextBox)ThisWindow.GetChildByName("NameBox");
            fileNameText.Text = _conditions.ActiveFileName;
            fileNameText.Invalidate();

            Update();
        } //todo: Updates into one method

        private void UpdateScrollBtns()
        {
            if (DrawingStartIndex == _conditions.MelodyBuffer.GetMelody().Count - DisplayedNoteCounter)
            {
                _gui.ToggleElement("ScrollRight", ThisWindow, false);
                _gui.ToggleElement("ToEnd", ThisWindow, false);
            }
            else
            {
                _gui.ToggleElement("ScrollRight", ThisWindow, true);
                _gui.ToggleElement("ToEnd", ThisWindow, true);
            }

            if (DrawingStartIndex == 0)
            {
                _gui.ToggleElement("ScrollLeft", ThisWindow, false);
                _gui.ToggleElement("ToStart", ThisWindow, false);
            }
            else
            {
                _gui.ToggleElement("ScrollLeft", ThisWindow, true);
                _gui.ToggleElement("ToStart", ThisWindow, true);
            }
        }

        private void Update()
        {
            if (_conditions.IsFileSaved)
                _gui.ToggleElement("SaveButton", ThisWindow, false);
            else
                _gui.ToggleElement("SaveButton", ThisWindow, true);
            
            if (_conditions.SelectedNote != -1)
            {
                _gui.ToggleElement("CopyButton", ThisWindow, true);
                _gui.ToggleElement("CloneButton", ThisWindow, true);
                _gui.ToggleElement("ReplaceButton", ThisWindow, true);
                _gui.ToggleElement("PlayNoteButton", ThisWindow, true);
                _gui.ToggleElement("DelButton", ThisWindow, true);
                Note temp = (Note)_conditions.MelodyBuffer.GetMelody()[_conditions.SelectedNote];
                if ((temp.GetPitch().OctaveShift != 1 || (temp.GetPitch().Symbol != Pitch.B && temp.GetPitch().Symbol != Pitch.Bb)) && temp.GetPitch().Symbol != Pitch.R)
                    _gui.ToggleElement("OctaveUp", ThisWindow, true);
                else
                    _gui.ToggleElement("OctaveUp", ThisWindow, false);
                if ((temp.GetPitch().OctaveShift != -1 || (temp.GetPitch().Symbol != Pitch.C && temp.GetPitch().Symbol != Pitch.Cs)) && temp.GetPitch().Symbol != Pitch.R)
                    _gui.ToggleElement("OctaveDown", ThisWindow, true);
                else
                    _gui.ToggleElement("OctaveDown", ThisWindow, false);
                _gui.ToggleElement("AddButton", ThisWindow, false);
                _gui.ToggleElement("PasteButton", ThisWindow, false);
            }
            if (_gui.Cursor.IsSet())
            {
                _gui.ToggleElement("CopyButton", ThisWindow, false);
                _gui.ToggleElement("CloneButton", ThisWindow, false);
                _gui.ToggleElement("ReplaceButton", ThisWindow, false);
                _gui.ToggleElement("PlayNoteButton", ThisWindow, false);
                _gui.ToggleElement("AddButton", ThisWindow, true);
                _gui.ToggleElement("DelButton", ThisWindow, true);
                _gui.ToggleElement("OctaveUp", ThisWindow, false);
                _gui.ToggleElement("OctaveDown", ThisWindow, false);
                if (_conditions.Clipboard != null)
                    _gui.ToggleElement("PasteButton", ThisWindow, true);
                else
                    _gui.ToggleElement("PasteButton", ThisWindow, false);
            }
            
            if (_gui.Cursor.IsAtStart())
                _gui.ToggleElement("DelButton", ThisWindow, false);
            if (_conditions.MelodyBuffer.GetMelody().Count == 0)
                DisableFunctions();
            else
            {
                _gui.ToggleElement("PlayButton", ThisWindow, true);
                _gui.ToggleElement("ClrButton", ThisWindow, true);
            }
        }
        
        private void DisableFunctions()
        {
            _gui.ToggleElement("PlayButton", ThisWindow, false);
            _gui.ToggleElement("ReplaceButton", ThisWindow, false);
            _gui.ToggleElement("DelButton", ThisWindow, false);
            _gui.ToggleElement("ClrButton", ThisWindow, false);
            _gui.ToggleElement("SaveButton", ThisWindow, false);
            _gui.ToggleElement("CloneButton", ThisWindow, false);
            _gui.ToggleElement("CopyButton", ThisWindow, false);
            _gui.ToggleElement("OctaveUp", ThisWindow, false);
            _gui.ToggleElement("OctaveDown", ThisWindow, false);
            if (_conditions.Clipboard == null)
                _gui.ToggleElement("PasteButton", ThisWindow, false);
        }
        
        private void PlayNoteBtnTapEvent(object sender)
        {
            _conditions.MelodyBuffer.PlayNote(_conditions.SelectedNote);
        }

        private void PasteBtnTapEvent(object sender)
        {
            _conditions.MelodyBuffer.InsertNote(new Note(_conditions.Clipboard), _gui.Cursor.GetPosition()+1); //it was just _conditions.Clipboard previously and invoking octave up or down was working on the same note; todo: look for such issues!
            _conditions.IsFileSaved = false;
            if (_gui.Cursor.GetPosition() - _gui.EditorWindow.DrawingStartIndex == _gui.EditorWindow.DisplayedNoteCounter - 1 && _gui.EditorWindow.XPos + _gui.EditorWindow.NoteWidth(_conditions.Clipboard) + CursorWidth > MelodyFieldBound)
                _gui.EditorWindow.DrawingStartIndex++;
            _staffDrawer.ClearMelodyField();
            XPos = 43;
            _staffDrawer.DrawMelodyField();
            UpdateScrollBtns();
            ThisWindow.Invalidate();
            _conditions.SelectedNote = _gui.Cursor.GetPosition() + 1;
            UnHighlightCursor();
            _gui.Cursor.Reset();
            HighlightNote();
            Update();
        }

        private void CopyBtnTapEvent(object sender)
        {
            _conditions.Clipboard = _conditions.MelodyBuffer.GetNote(_conditions.SelectedNote);
        }

        private void CloneBtnTapEvent(object sender)
        {
            _conditions.MelodyBuffer.CloneNote(_conditions.SelectedNote);
            if (_conditions.SelectedNote - _gui.EditorWindow.DrawingStartIndex == _gui.EditorWindow.DisplayedNoteCounter - 1 && _gui.EditorWindow.XPos + _gui.EditorWindow.NoteWidth((Note)_conditions.MelodyBuffer.GetMelody()[_conditions.SelectedNote]) + CursorWidth > MelodyFieldBound)
                _gui.EditorWindow.DrawingStartIndex++;
            _staffDrawer.ClearMelodyField();
            XPos = 43;
            _staffDrawer.DrawMelodyField();
            UpdateScrollBtns();
            _conditions.IsFileSaved = false;
            ThisWindow.Invalidate();
            _conditions.SelectedNote = _conditions.SelectedNote+1;
            HighlightNote();
        }

        private void ToEndBtnTapEvent(object sender)
        {
            RespawnMelodyFieldWithContent(true, _conditions.MelodyBuffer.GetMelody().Count - DisplayedNoteCounter - DrawingStartIndex); //amount
            _gui.Cursor.SetPosition(DisplayedNoteCounter+DrawingStartIndex-1);
            HighlightCursor();
        }

        private void ToStartBtnTapEvent(object sender)
        {
            RespawnMelodyFieldWithContent(false, DrawingStartIndex);
            _gui.Cursor.BringToStart();
            HighlightCursor();
        }

        private void RightBtnTapEvent(object sender)
        {
            RespawnMelodyFieldWithContent(true, 1);
            if (NoteVisible())
                HighlightNote();
            if (CursorVisible())
                HighlightCursor();
        }

        private void LeftBtnTapEvent(object sender)
        {
            RespawnMelodyFieldWithContent(false, 1);
            if (NoteVisible())
                HighlightNote();
            if (CursorVisible())
                HighlightCursor();
        }

        private void OctaveDownBtnTapEvent(object sender)
        {
            Note temp = (Note)_conditions.MelodyBuffer.GetMelody()[_conditions.SelectedNote];
            int newOctaveShift;
            double newSymbol;
            if (temp.GetPitch().Symbol == Pitch.C || temp.GetPitch().Symbol == Pitch.Cs)
            {
                newOctaveShift = temp.GetPitch().OctaveShift-1;
                newSymbol = (double)Pitch.Symbols["B"];
            }
            else
            {
                newOctaveShift = temp.GetPitch().OctaveShift;
                newSymbol = (double)Pitch.Symbols[Pitch.PitchIndex[(int)Pitch.PitchIndex[temp.GetPitch().Symbol] - 1]];
            }
            if (temp.GetPitch().Symbol == Pitch.Gs)
                newSymbol = Pitch.Fs;

            temp.SetPitch(new Pitch(newSymbol, newOctaveShift));

            _conditions.MelodyBuffer.ReplaceNote(temp, _conditions.SelectedNote);
            _staffDrawer.ClearMelodyField(); //these three lines are written too many times - encapsulate or something
            XPos = 43;
            _staffDrawer.DrawMelodyField();
            _conditions.IsFileSaved = false;
            ThisWindow.Invalidate();
            HighlightNote();
            Update();
        }

        private void OctaveUpBtnTapEvent(object sender) //method inside also can be encapsulated I think
        {
            Note temp = (Note)_conditions.MelodyBuffer.GetMelody()[_conditions.SelectedNote];
            int newOctaveShift;
            double newSymbol;
            if (temp.GetPitch().Symbol == Pitch.B || temp.GetPitch().Symbol == Pitch.Bb)
            {
                newOctaveShift = temp.GetPitch().OctaveShift + 1;
                newSymbol = (double)Pitch.Symbols["C"];
            }
            else
            {
                newOctaveShift = temp.GetPitch().OctaveShift;
                newSymbol = (double)Pitch.Symbols[Pitch.PitchIndex[(int)Pitch.PitchIndex[temp.GetPitch().Symbol] + 1]];
            }
            if (temp.GetPitch().Symbol == Pitch.Fs)
                newSymbol = Pitch.Gs;
            
            temp.SetPitch(new Pitch(newSymbol, newOctaveShift));

            _conditions.MelodyBuffer.ReplaceNote(temp, _conditions.SelectedNote);
            _staffDrawer.ClearMelodyField();
            XPos = 43;
            _staffDrawer.DrawMelodyField();
            _conditions.IsFileSaved = false;
            ThisWindow.Invalidate();
            HighlightNote();
            Update();
        }
        
        private void RespawnMelodyFieldWithContent(bool scrollingDirection, int amount)
        {
            _staffDrawer.ClearMelodyField();
            
            if (scrollingDirection)
                DrawingStartIndex += amount;
            else
                DrawingStartIndex -= amount;

            XPos = 43;
            _staffDrawer.DrawMelodyField();

            ThisWindow.Invalidate();
            UpdateScrollBtns();
        }
        
        private void HighlightNote()
        {
            var setImage = (Image)ThisWindow.GetChildByName("Note" + _conditions.SelectedNote);
            var current = (Note)_conditions.MelodyBuffer.GetMelody()[_conditions.SelectedNote];
            var targetKey = (string)Duration.Durations[current.GetDuration()];
            if (current.IsRest())
            {
                targetKey += "RestTh";
            }
            else
            {
                targetKey += "NoteTh";
            }
            setImage.Bitmap = (Bitmap)_noteImageResources[targetKey + "_1"];
            var backColor = setImage.Bitmap.GetPixel(0, 0);
            setImage.Bitmap.MakeTransparent(backColor);
            SelectAdditionals();
            setImage.Invalidate();
        }

        private void SelectAdditionals()
        {
            var current = (Note)_conditions.MelodyBuffer.GetMelody()[_conditions.SelectedNote];
            if (current.IsFlat())
            {
                var setImage = (Image)ThisWindow.GetChildByName("Flat" + _conditions.SelectedNote);
                setImage.Bitmap = (Bitmap)_noteImageResources["flatTh_1"];
                var backColor = setImage.Bitmap.GetPixel(0, 0);
                setImage.Bitmap.MakeTransparent(backColor);
                setImage.Invalidate();
            }
            if (current.IsSharp())
            {
                var setImage = (Image)ThisWindow.GetChildByName("Sharp" + _conditions.SelectedNote);
                setImage.Bitmap = (Bitmap)_noteImageResources["sharpTh_1"];
                var backColor = setImage.Bitmap.GetPixel(0, 0);
                setImage.Bitmap.MakeTransparent(backColor);
                setImage.Invalidate();
            }
            if (current.IsDotted())
            {
                var setImage = (Image)ThisWindow.GetChildByName("Dot" + _conditions.SelectedNote);
                setImage.Bitmap = (Bitmap)_noteImageResources["dotTh_1"];
                var backColor = setImage.Bitmap.GetPixel(0, 0);
                setImage.Bitmap.MakeTransparent(backColor);
                setImage.Invalidate();
            }
            if (current.IsStaccato())
            {
                var setImage = (Image)ThisWindow.GetChildByName("Staccato" + _conditions.SelectedNote);
                setImage.Bitmap = (Bitmap)_noteImageResources["staccatoTh_1"];
                var backColor = setImage.Bitmap.GetPixel(0, 0);
                setImage.Bitmap.MakeTransparent(backColor);
                setImage.Invalidate();
            }
        }

        public void UnHighlightNote()
        {
            var setImage = (Image)ThisWindow.GetChildByName("Note" + _conditions.SelectedNote);
            var current = (Note)_conditions.MelodyBuffer.GetMelody()[_conditions.SelectedNote];
            var targetKey = (string)Duration.Durations[current.GetDuration()];
            if (current.IsRest())
                targetKey += "RestTh";
            else
                targetKey += "NoteTh";
            setImage.Bitmap = (Bitmap)_noteImageResources[targetKey];
            var backColor = setImage.Bitmap.GetPixel(0, 0);
            setImage.Bitmap.MakeTransparent(backColor);
            DeselectAdditionals();
            setImage.Invalidate();
        }

        private void DeselectAdditionals()
        {
            var current = (Note)_conditions.MelodyBuffer.GetMelody()[_conditions.SelectedNote];
            if (current.IsFlat())
            {
                var setImage = (Image)ThisWindow.GetChildByName("Flat" + _conditions.SelectedNote);
                setImage.Bitmap = (Bitmap)_noteImageResources["flatTh"];
                var backColor = setImage.Bitmap.GetPixel(0, 0);
                setImage.Bitmap.MakeTransparent(backColor);
                setImage.Invalidate();
            }
            if (current.IsSharp())
            {
                var setImage = (Image)ThisWindow.GetChildByName("Sharp" + _conditions.SelectedNote);
                setImage.Bitmap = (Bitmap)_noteImageResources["sharpTh"];
                var backColor = setImage.Bitmap.GetPixel(0, 0);
                setImage.Bitmap.MakeTransparent(backColor);
                setImage.Invalidate();
            }
            if (current.IsDotted())
            {
                var setImage = (Image)ThisWindow.GetChildByName("Dot" + _conditions.SelectedNote);
                setImage.Bitmap = (Bitmap)_noteImageResources["dotTh"];
                var backColor = setImage.Bitmap.GetPixel(0, 0);
                setImage.Bitmap.MakeTransparent(backColor);
                setImage.Invalidate();
            }
            if (current.IsStaccato())
            {
                var setImage = (Image)ThisWindow.GetChildByName("Staccato" + _conditions.SelectedNote);
                setImage.Bitmap = (Bitmap)_noteImageResources["staccatoTh"];
                var backColor = setImage.Bitmap.GetPixel(0, 0);
                setImage.Bitmap.MakeTransparent(backColor);
                setImage.Invalidate();
            }
        }

        public void ElementImgTapEvent(object sender)
        {
            sender.GetType();
            var tappedOne = (Image)sender;

            if (tappedOne.Name.Substring(0, 3) == "Dot")
            {
                if (_conditions.SelectedNote == int.Parse(tappedOne.Name.Substring(3)))
                    return;
                if (NoteVisible())
                    UnHighlightNote();
                if (CursorVisible())
                {
                    UnHighlightCursor();
                    _gui.Cursor.Reset();
                }
                _conditions.SelectedNote = int.Parse(tappedOne.Name.Substring(3));
                HighlightNote();
                Update();
                return;
            }
            if (tappedOne.Name.Substring(0, 4) == "Flat")
            {
                if (_conditions.SelectedNote == int.Parse(tappedOne.Name.Substring(4)))
                    return;
                if (NoteVisible())
                    UnHighlightNote();
                if (CursorVisible())
                {
                    UnHighlightCursor();
                    _gui.Cursor.Reset();
                }
                _conditions.SelectedNote = int.Parse(tappedOne.Name.Substring(4));
                HighlightNote();
                Update();
                return;
            }
            if (tappedOne.Name.Substring(0, 4) == "Note")
            {
                if (_conditions.SelectedNote == int.Parse(tappedOne.Name.Substring(4)))
                    return;
                if (NoteVisible())
                    UnHighlightNote();
                if (CursorVisible())
                {
                    UnHighlightCursor();
                    _gui.Cursor.Reset();
                }
                _conditions.SelectedNote = int.Parse(tappedOne.Name.Substring(4));
                HighlightNote();
                Update();
                return;
            }
            if (tappedOne.Name.Substring(0, 5) == "Sharp")
            {
                if (_conditions.SelectedNote == int.Parse(tappedOne.Name.Substring(5)))
                    return;
                if (NoteVisible())
                    UnHighlightNote();
                if (CursorVisible())
                {
                    UnHighlightCursor();
                    _gui.Cursor.Reset();
                }
                _conditions.SelectedNote = int.Parse(tappedOne.Name.Substring(5));
                HighlightNote();
                Update();
                return;
            }
            if (tappedOne.Name.Substring(0, 6) == "Cursor")
            {
                if (_gui.Cursor.GetPosition() == int.Parse(tappedOne.Name.Substring(6)))
                    return;
                if (CursorVisible())
                    UnHighlightCursor();
                if (NoteVisible())
                {
                    UnHighlightNote();
                    _conditions.SelectedNote = -1;
                }
                _gui.Cursor.SetPosition(int.Parse(tappedOne.Name.Substring(6)));
                HighlightCursor();
                Update();
                return;
            }
            if (tappedOne.Name.Substring(0, 8) == "Staccato")
            {
                if (_conditions.SelectedNote == int.Parse(tappedOne.Name.Substring(8)))
                    return;
                if (NoteVisible())
                    UnHighlightNote();
                if (CursorVisible())
                {
                    UnHighlightCursor();
                    _gui.Cursor.Reset();
                }
                _conditions.SelectedNote = int.Parse(tappedOne.Name.Substring(8));
                HighlightNote();
                Update();
                return;
            }
        }

        private bool NoteVisible()
        {
            return _conditions.SelectedNote != -1 && _conditions.SelectedNote >= DrawingStartIndex && _conditions.SelectedNote < DrawingStartIndex+DisplayedNoteCounter;
        }

        private bool CursorVisible()
        {
            return _gui.Cursor.IsSet() && _gui.Cursor.GetPosition() >= DrawingStartIndex - 1 && _gui.Cursor.GetPosition() < DrawingStartIndex + DisplayedNoteCounter;
        }

        private void SaveBtnTapEvent(object sender)
        { //todo: after NETMF 4.2
            /*var path = _conditions.Drive.Volume.RootDirectory + @"\" + _conditions.ActiveFileName + ".tsm";
            using (var logStream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
            {
                var fileContent = Encoding.UTF8.GetBytes(_conditions.MelodyBuffer.ToString());
                logStream.Write(fileContent, 0, fileContent.Length);
                logStream.Flush();
                logStream.Close();
            }*/
            _conditions.IsFileSaved = true;
            
            Update();
        }

        private void ClrBtnTapEvent(object sender)
        {
            _conditions.MelodyBuffer.ClearMelody();
            _staffDrawer.ClearMelodyField();
            XPos = 43;
            _staffDrawer.DrawMelodyField();
            UpdateScrollBtns();
            _conditions.IsFileSaved = false;
            _conditions.SelectedNote = -1;
            _gui.Cursor.BringToStart();
            Update();
            ThisWindow.Invalidate();
            HighlightCursor();
        }

        private void QuitBtnTapEvent(object sender)
        {
            if (!_conditions.IsFileSaved)
            {
                XPos = 43;
                _gui.CancelQuestionBox.SetToMain();
            }
            else
            {
                _gui.MainMenuWindow.SetToMain();
                _conditions.MelodyBuffer = null;
                _conditions.Clipboard = null;
                DrawingStartIndex = 0;
                if (_gui.Cursor.IsSet())
                    UnHighlightCursor();
                _conditions.SelectedNote = -1;
                _gui.Cursor.BringToStart();
                XPos = 43;
            }
        }

        private void AddBtnTapEvent(object sender)
        {
            _conditions.ReplaceMenu = false;
            _gui.NoteInputWindow.SetToMain();
        }

        private void DelBtnTapEvent(object sender)
        {
            if (_gui.Cursor.IsSet())
                _conditions.MelodyBuffer.RemoveNote(_gui.Cursor.GetPosition());
            if (_conditions.SelectedNote != -1)
                _conditions.MelodyBuffer.RemoveNote(_conditions.SelectedNote);
            _conditions.IsFileSaved = false;
            _staffDrawer.ClearMelodyField();
            XPos = 43;
            _staffDrawer.DrawMelodyField();
            UpdateScrollBtns();
            ThisWindow.Invalidate();
            if (_gui.Cursor.IsAtStart())
                HighlightCursor();
            if (_gui.Cursor.GetPosition() > -1)
            {
                _gui.Cursor.DecrementPosition();
                HighlightCursor();
            }
            if (_conditions.SelectedNote == 0)
            {
                _conditions.SelectedNote = _conditions.SelectedNote - 1;
                _gui.Cursor.BringToStart();
                HighlightCursor();
            }
            if (_conditions.SelectedNote > 0)
            {
                _conditions.SelectedNote = _conditions.SelectedNote-1;
                HighlightNote();
            }
            Update();
        }

        private void ReplBtnTapEvent(object sender)
        {
            _conditions.ReplaceMenu = true;
            _gui.NoteInputWindow.SetToMain();
        }

        private void BaseOctaveBoxTapEvent(object sender)
        {
            _conditions.BaseOctaveMenu = true;
            _gui.NumericalInputWindow.SetToMain();
        }

        private void PlayBtnTapEvent(object sender)
        {
            _conditions.MelodyBuffer.PlayMelody();
        }

        private void NameBoxTapEvent(object sender)
        {
            Glide.OpenKeyboard(sender); //todo: file name validation
        }

        private void BpmBoxTapEvent(object sender)
        {
            _conditions.BaseOctaveMenu = false;
            _gui.NumericalInputWindow.SetToMain();
        }
        
        public int NoteWidth(Note tempNote)
        {
            return _staffDrawer.NoteWidth(tempNote);
        }

        private void HighlightCursor()
        {
            var setImage = (Image)ThisWindow.GetChildByName("Cursor" + _gui.Cursor.GetPosition());
            setImage.Alpha = 64;
            setImage.Invalidate();
        }

        private void UnHighlightCursor()
        {
            var setImage = (Image)ThisWindow.GetChildByName("Cursor" + _gui.Cursor.GetPosition());
            ThisWindow.RemoveChild(setImage);
            ThisWindow.Render();
            setImage.Alpha = 4;
            ThisWindow.AddChild(setImage);
            setImage.Invalidate();
        }
    }
}
